package com.atguigu.tingshu.album.consumer;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author Taeyang
 * @date 2025/5/2
 */
@Component
@Log4j2
public class RedisAlbumConsumer {
    private final RedisTemplate redisTemplate;

    @Autowired
    public RedisAlbumConsumer(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @SneakyThrows
    @RabbitListener(queues = "redis_queue")
    public void redisAlbumDelete(Channel channel, Message message) {
        String s = new String(message.getBody());
        // 获取消息
        Long albumId = Long.valueOf(s);
        // 组装需要删除的Redis数据的key
        String albumInfoKey = RedisConstant.ALBUM_INFO_PREFIX + "[" + albumId + "]";
        // 获取消息的属性
        MessageProperties messageProperties = message.getMessageProperties();
        // 获取消息的编号
        long deliveryTag = messageProperties.getDeliveryTag();
        try {
            // 执行删除
            redisTemplate.delete(albumInfoKey);
            redisTemplate.expire(albumInfoKey, 1, TimeUnit.SECONDS);
            // 确认消息
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            e.printStackTrace();
            // 异常捕获，再来一次
            if (messageProperties.getRedelivered()) {
                channel.basicReject(deliveryTag, false);
            } else {
                channel.basicReject(deliveryTag, true);
            }
        }
    }
}
